import Markdown from "react-markdown";
import remarkGfm from "remark-gfm"
import styles from './aiChat.module.css';
import { useContext, useState } from "react";
import { knows, heart, zhuai } from '../../assist/gif/gif'
import { Button, Drawer } from 'antd';
import { createContext } from "react";
// import Loading from "react-loading";
// import ReactLoading from 'react-loading';
// Mock 对话数据（没有传入对话历史参数时使用）

const chatHistory = [
    {"id":0, "time":'2024/09/14', "text":'什么是ai?'},
    {"id":1, "time":'2025/01/01', "text":'ai是什么?'},
    {"id":2, "time":'2025/06/07', "text":'ai是什么?'},
    {"id":3, "time":'2025/09/01', "text":'你好，这是 ai 聊天机器人。'}
]

const chatMockData = [
    {"id": 0, "identity": "user", "text": "hello."},
    {"id": 1, "identity": "ai", "text":"hello, how are you?"},
    {"id": 2, "identity": "user", "text":"I am fine, how are you?"},
    {"id": 3, "identity": "ai", "text":"I am fine, thanks."},
    {"id": 4, "identity": "user", "text":"I am fine, how are you?"},
    {"id": 5, "identity": "ai", "text":"I am fine, thanks."},
    {"id": 6, "identity": "user", "text":"I am fine, how are you?"},
    {"id": 7, "identity": "ai", "text":"I am fine, thanks."},
    {"id": 8, "identity": "user", "text":"I am fine, how are you?"},
    {"id": 9, "identity": "ai", "text":"I am fine, thanks."},
    {"id": 10, "identity": "user", "text":"I am fine, how are you?"},
    {"id": 11, "identity": "ai", "text":"I am fine, thanks."},
    {"id": 12, "identity": "user", "text":"I am fine, how are you?"},
    {"id": 13, "identity": "ai", "text":"I am fine, thanks."},
    {"id": 14, "identity": "user", "text":"I am fine, how are you?"},
    {"id": 15, "identity": "ai", "text":`# markdown 示例
## 1. 基础语法
- **加粗文本**
- *斜体文本*
- \`行内代码\`
- [链接](https://example.com)
- ~~删除线~~
- Markdown 是一种轻量级标记语言，它允许人们使用易读易写的纯文本格式编写文档。Markdown 语言在 2004 由约翰·格鲁伯（英语：John Gruber）创建。Markdown 编写的文档可以导出 HTML 、Word、图像、PDF、Epub 等多种格式的文档。

## 2. 代码块
\`\`\`javascript
// 代码高亮示例
function hello() {
console.log('Hello Markdown!');
}
\`\`\`

## 3. 表格

| 名称 | 功能 |
|------|------|
| vue3-markdown-it | Markdown渲染组件 |
| markdown-it | 核心解析器 |

## 4. 表情支持 :smile:

:laughing: :tada:

## 5. 上标和下标
- 上标：2^10^ = 1024
- 下标：H~2~O

## 目录
[[toc]]
`}
]
const chatDataContext = createContext()

const chatMockChangeData = [
    {"id": 0, "identity": "user", "text": "hello."},
    {"id": 1, "identity": "ai", "text":"change"},
    {"id": 2, "identity": "user", "text":"changed"},
    {"id": 3, "identity": "ai", "text":"change"},
    {"id": 4, "identity": "user", "text":"changed"},
    {"id": 5, "identity": "ai", "text":"change"},
    {"id": 4, "identity": "user", "text":"changed"},
    {"id": 5, "identity": "ai", "text":"change"},
    {"id": 4, "identity": "user", "text":"changed"},
    {"id": 5, "identity": "ai", "text":"change"},
    {"id": 4, "identity": "user", "text":"changed"},
    {"id": 5, "identity": "ai", "text":"change"},
]
// const chatMockData = [] // When chatMockData is null

// 默认使用的接口函数（没有传入api相关参数时使用）
async function aiChatApiFunction() {
    return await fetch('/api/stream-data', {
        method: 'GET',
        headers: {
        'Accept': 'text/event-stream',
        },
    });
}
// // 加载动画
// const Loading = (type, color) => {
//     return (
//         <ReactLoading type={type} color={color} height={'20%'} width={'20%'} />
//     )
// }

// 对话历史列表
const ChatHistoryList = ({ chatHistory }) => {
    const [chatMockListData, setChatMockListData] = useState(chatMockData)
    // 切换对话列表
    const changeChatList = () => {
        setChatMockListData(chatMockChangeData)
    }
    return (
        <div
            className={styles.chatHistoryList}
            style={{display:'flex', flexDirection: 'column'}}
        >
            {chatHistory.map((item) => (
                <Button className={styles.chatHistoryListItem} onClick={changeChatList}>
                    <div style={{fontSize: 'small', fontWeight: '400'}}>{item.time}</div>
                    {item.text}
                </Button>
            ))}
        </div>
    )
}
// 对话侧边栏
const ChatManageDrawer = ({ open, close }) => {
    return (
        <Drawer
            title="Deal Chat"
            closable={{ 'aria-label': 'Close Button' }}
            onClose={close}
            open={open}
        >
            <ChatHistoryList chatHistory={chatHistory} />
      </Drawer>
    )
}
// 标题栏
const Header = () => {
    const [open, setOpen] = useState(false);
    const [, setChatData] = useContext(chatDataContext)
    const showDrawer = () => {
        setOpen(true);
    };
    const closeDrawer = () => {
        setOpen(false);
    };

    const deleteLocalHistory = () => {
        setChatData([])
    }

    return (
        <div className={styles.header}>
            <h1 style={{fontStyle: 'italic', color: 'white', marginLeft: '10px'}}>AiChatView</h1>
            <Button
                type="primary"
                onClick={showDrawer}
                style={{marginLeft:'5px', backgroundColor:'#d8f185', color:'gray'}}
                title='打开列表'
            >
                Open list
            </Button>
            <Button
                type="primary"
                onClick={deleteLocalHistory}
                style={{marginLeft:'5px'}}
                title="清空本地对话记录"
            >
                clear
            </Button>
            <ChatManageDrawer open={open} close={closeDrawer} />
        </div>
    )
}
// 对话框（ai）
const ChatItem_ai = (item) => {
    return (
        <div key={item.id} className={`${styles.chatItem} ${styles.ai}`}>
            <Markdown remarkPlugins={[remarkGfm]}>{item.text}</Markdown>
        </div>
    )
};
// 对话框（用户）
const ChatItem_user = (item) => {
    return (
        <div key={item.id} className={`${styles.chatItem} ${styles.user}`}>
            {item.text}
        </div>
    )
};
// 输入框
const TypeBox = ({ onSendMessage }) => {
    const [text, setText] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const [, setError] = useState(null);
    // 发送消息方法
    const sendMessage = async() => {
        setText('');
        if (!text.trim()) return;
        setIsLoading(true);
        setError(null);
        try {
            // 调用父组件传递的回调函数发送消息
            onSendMessage(text);
            const response = await aiChatApiFunction();
            // if (chatApiFunction) {
            //     response = await chatApiFunction();
            // } else{
            //     response = await aiChatApiFunction();
            // }
            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }
            // 获取响应体的可读流
            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let accumulatedText = '';
            // 循环读取流数据
            while (true) {
                const { done, value } = await reader.read();
                // 如果流结束，退出循环
                if (done) { break; }
                // 解码新收到的数据并更新状态
                const chunk = decoder.decode(value, { stream: true });
                accumulatedText += chunk;
                // 更新流式数据状态
                onSendMessage(null, accumulatedText);
            }
        } catch (err) {
            setError(err.message);
            window.alert('发生错误',err);
            onSendMessage(null, '抱歉，回复失败，请重试');
        } finally {
            setIsLoading(false);
        }
    }

    return (
        <div className={styles.inputContainer}>
            <textarea
                className={styles.typeBox}
                placeholder={isLoading ? '加载中，正在接收数据...' : '请输入...'}
                value={text}
                onChange={(e) => setText(e.target.value)}
                disabled={isLoading}
            />
            <button
                className={styles.sendButton}
                onClick={sendMessage}
                style={{
                    backgroundColor: isLoading || !text.trim() ? '#ccc' : '#007bff',
                }}
            >
                ▲
            </button>
        </div>
    )
};
// 空对话列表占位符
const chatListPlaceholder = () => {
    function selectGif() {
        const gifs = [knows,heart,zhuai]
        return gifs[Math.floor(Math.random() * gifs.length)]
    }
    return (
        <div className={styles.chatItem}>
            <img
                src={selectGif()}
                alt="knowsGif"
                style={{ width: '150px', height: '150px',margin: 'auto', marginTop: '20%' }}
            />
            <h2 style={{margin: 'auto'}}>尝试输入点什么</h2>
            <h4 style={{margin: 'auto'}}>我来为你解答 :）</h4>
        </div>
    )
};
// 对话列表
const AiChatList = ({ chatData }) => {
    return (
        <div className={styles.chatView}>
            {chatData.length === 0 && chatListPlaceholder()}
            {chatData.map((item) => {
                if (item.identity === "ai") {
                    return ChatItem_ai(item)
                } else {
                    return ChatItem_user(item)
                }
            })}
        </div>
    )
};
// main组件
const Aichat = (props) => {
    const [chatData, setChatData] = useState(chatMockData);
    const handleSendMessage = (userText, aiText) => {
        if (userText) {
            // 添加用户消息
            const newUserMessage = {
                id: Date.now(),
                identity: 'user',
                text: userText
            };
            setChatData(prev => [...prev, newUserMessage]);
            // 添加AI消息占位符
            const newAiMessage = {
                id: Date.now() + 1,
                identity: 'ai',
                text: '正在思考...'
            };
            setChatData(prev => [...prev, newAiMessage]);
        } else if (aiText !== undefined) {
            // 更新AI消息
            setChatData(prev => {
                const updated = [...prev];
                const lastAiIndex = updated.length - 1;
                if (lastAiIndex >= 0 && updated[lastAiIndex].identity === 'ai') {
                    updated[lastAiIndex] = {
                        ...updated[lastAiIndex],
                        text: aiText
                    };
                }
                return updated;
            });
        }
    };

    return (
        <chatDataContext.Provider value={[chatData, setChatData]}>
            <div value={[chatData, setChatData]} className={styles.aiChatContainer}>
                <Header />
                <AiChatList chatData={chatData}  />
                <TypeBox onSendMessage={handleSendMessage} />
            </div>
        </chatDataContext.Provider>
    )
};

export default Aichat;